using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MKDS_Course_Editor.GCN
{
    public static class Helper
    {
        public static void toWORD(UInt16 w)
        {
            byte w1 = (byte)(w & 0xFF);
            byte w2 = (byte)(w >> 8);
            w = (ushort)((w1 << 8) | w2);
        }

        public static void toSHORT(UInt16 w)
        {
            toWORD((UInt16)w);
        }

        public static void toDWORD(UInt32 d)
        {
            byte w1 = (byte)(d & 0xFF);
            byte w2 = (byte)((d >> 8) & 0xFF);
            byte w3 = (byte)((d >> 16) & 0xFF);
            byte w4 = (byte)(d >> 24);
            d = (UInt32)((w1 << 24) | (w2 << 16) | (w3 << 8) | w4);
        }

        public static void toFLOAT(float f)
        { toDWORD((UInt32)f); }
        public static int max(int a, int b)
        {
            return a > b ? a : b;
        }
        public static void readStringtable(int pos, EndianBinaryReader er, List<string> dest)
        {
            long oldPos = er.BaseStream.Position;

            er.BaseStream.Position = pos;

            UInt16 count = er.ReadUInt16(); toWORD(count);
            er.BaseStream.Position += 2; //skip pad bytes

            for (int i = 0; i < count; ++i)
            {
                UInt16 unknown, stringOffset;
                unknown = er.ReadUInt16(); toWORD(unknown);
                stringOffset = er.ReadUInt16(); toWORD(stringOffset);
                string s = getString(pos + stringOffset, er);
                dest.Add(s);
            }

            er.BaseStream.Position = oldPos;
        }
        private static string getString(int pos, EndianBinaryReader er)
        {
            int t = (int)er.BaseStream.Position;
            er.BaseStream.Position = pos;

            string ret = "";
            char c;
            while ((c = er.ReadChar(Encoding.ASCII)) != '\0')
                ret += c;

            er.BaseStream.Position = t;

            return ret;
        }
        public static Int16 memWORD(byte[] where)
        {
            return (Int16)((where[0] << 8) | where[1]);
        }

        public static Int32 memDWORD(byte[] where)
        {
            return (where[0] << 24) | (where[1] << 16) | (where[2] << 8) | where[3];
        }
        /*private UInt16 aWORD(u16 w)
        {
          toWORD(w); return w;
        }

        inline s16 aSHORT(s16 s)
        {
          return aWORD(*(u16*)&s);
        }

        inline u32 aDWORD(u32 d)
        {
          toDWORD(d); return d;
        }

        inline f32 aFLOAT(f32 f)
        {
          toFLOAT(f); return f;
        }*/
    }
}
